package org.example.cloudcommon.qiniu;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;

/**
 * 七牛云
 */
@RequestMapping("/qiniu")
@RestController
public class QiniuController {
    @Autowired
    QiniuProperties properties;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file){
        //构造一个带指定 Region 对象的配置类 up-z2.qiniup.com
        // Configuration cfg = new Configuration(Region.huadong());
        Configuration cfg = new Configuration(Zone.zone2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(properties.getAccessKey(), properties.getSecretKey());
        String upToken = auth.uploadToken(properties.getBucketName());
        try {
            Response response = uploadManager.put(file.getBytes(), file.getOriginalFilename(), upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hashCode());
            String encodedFileName = URLEncoder.encode(file.getOriginalFilename(), "utf-8").replace("+", "%20");
            String finalUrl = String.format("%s/%s", properties.getPrefixUrl(), encodedFileName);
            System.out.println(finalUrl);
            return finalUrl;
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @PostMapping("/qiniuDelete/{name}")
    public void delete(@PathVariable String name){
        Auth auth = Auth.create(properties.getAccessKey(), properties.getSecretKey());
        Configuration config = new Configuration(Zone.zone2());
        BucketManager bucketMgr = new BucketManager(auth, config);
        //指定需要删除的文件，和文件所在的存储空间
        String bucketName = properties.getBucketName();
        String  key = name;
        try {
            Response delete = bucketMgr.delete(bucketName, key);
            delete.close();
            System.out.println(delete.statusCode);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("结束了");
    }

    @PostMapping("/load/{name}")
    public String getLoadUrl(@PathVariable String name) {
        StringBuilder str = new StringBuilder();
        StringBuilder append = str.append(properties.getPrefixUrl()).append("/").append(name);
        System.out.println(append);
        Auth auth = Auth.create(properties.getAccessKey(), properties.getSecretKey());
        String downloadUrl = auth.privateDownloadUrl(String.valueOf(append));
        return downloadUrl;
    }


}
